<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>DNS Tools</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      body {
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
          sans-serif;
        background-color: #f5f5f5;
        color: #333;
        line-height: 1.6;
      }

      /* 手机适配 */
      @media (max-width: 768px) {
        .container {
          padding: 0 10px;
        }

        .tabs {
          flex-wrap: wrap;
          margin-top: 10px;
        }

        .tab {
          flex: 1;
          min-width: calc(50% - 5px);
          margin: 2px;
          padding: 10px 15px;
          font-size: 14px;
          text-align: center;
        }

        .content {
          padding: 15px;
          min-height: 300px;
        }

        input,
        select,
        textarea {
          font-size: 16px; /* 防止iOS缩放 */
        }

        button {
          width: 100%;
          padding: 12px;
          font-size: 16px;
          margin-top: 10px;
        }

        h1 {
          font-size: 20px;
        }

        .result {
          margin-top: 15px;
          padding: 15px;
          font-size: 14px;
        }

        .result pre {
          font-size: 12px;
          overflow-x: auto;
        }
      }

      header {
        background-color: #2196f3;
        color: white;
        padding: 1rem 0;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }

      .header-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .region-switcher {
        display: flex;
        align-items: center;
        gap: 10px;
      }

      .region-switcher label {
        font-size: 14px;
        opacity: 0.9;
      }

      .region-switcher select {
        padding: 6px 12px;
        border: 1px solid rgba(255, 255, 255, 0.3);
        background: rgba(255, 255, 255, 0.1);
        color: white;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
      }

      .region-switcher select option {
        background: #2196f3;
        color: white;
      }

      @media (max-width: 768px) {
        .header-content {
          flex-direction: column;
          gap: 10px;
        }

        .region-switcher {
          width: 100%;
          justify-content: center;
        }
      }

      .container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 0 20px;
      }

      @media (max-width: 480px) {
        .container {
          padding: 0 10px;
        }
      }

      h1 {
        font-size: 24px;
        font-weight: 500;
      }

      .tabs {
        display: flex;
        background: #f5f5f5;
        border-radius: 8px 8px 0 0;
        margin-top: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }

      @media (max-width: 768px) {
        .tabs {
          flex-wrap: wrap;
          margin-top: 15px;
          border-radius: 8px;
        }
      }

      .tab {
        padding: 15px 30px;
        cursor: pointer;
        border: none;
        background: #f5f5f5;
        color: #666;
        font-size: 16px;
        transition: all 0.3s;
        border-bottom: 2px solid transparent;
        border-radius: 8px 8px 0 0;
      }

      .tab:hover {
        background-color: #e0e0e0;
        color: #333;
      }

      .tab.active {
        background: white;
        color: #2196f3;
        border-bottom: 2px solid #2196f3;
      }

      .content {
        background: white;
        padding: 30px;
        border-radius: 0 0 8px 8px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        min-height: 400px;
      }

      .form-group {
        margin-bottom: 20px;
      }

      label {
        display: block;
        margin-bottom: 5px;
        font-weight: 500;
      }

      input,
      select,
      textarea {
        width: 100%;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
      }

      button {
        background-color: #2196f3;
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        transition: background-color 0.3s;
      }

      button:hover {
        background-color: #1976d2;
      }

      .result {
        margin-top: 20px;
        padding: 20px;
        background-color: #f9f9f9;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
      }

      .result pre {
        white-space: pre-wrap;
        word-wrap: break-word;
      }

      .loading {
        display: inline-block;
        width: 20px;
        height: 20px;
        border: 3px solid #f3f3f3;
        border-top: 3px solid #2196f3;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-left: 10px;
      }

      @keyframes spin {
        0% {
          transform: rotate(0deg);
        }
        100% {
          transform: rotate(360deg);
        }
      }
    </style>
  </head>
  <body>
    <header>
      <div class="container">
        <div class="header-content">
          <h1>DNS Tools</h1>
          <div class="region-switcher">
            <select
              title="区域切换"
              id="region-select"
              onchange="switchRegion(this.value)"
            >
              <!-- Options will be loaded dynamically -->
            </select>
          </div>
        </div>
      </div>
    </header>

    <div class="container">
      <div class="tabs">
        <button class="tab active" onclick="showTab('verify')">域名验证</button>
        <button class="tab" onclick="showTab('dns')">DNS查询</button>
        <button class="tab" onclick="showTab('whois')">WHOIS查询</button>
        <button class="tab" onclick="showTab('link')">链接查询</button>
      </div>

      <div class="content">
        <!-- 域名验证 -->
        <div id="verify-tab" class="tab-content">
          <form onsubmit="verifyDomains(); return false;">
            <div class="form-group">
              <label for="verify-domains">域名（每行一个）</label>
              <textarea
                id="verify-domains"
                rows="6"
                placeholder="请输入域名，每行一个"
              ></textarea>
            </div>
            <div class="form-group">
              <label for="verify-brand">证书品牌</label>
              <select id="verify-brand">
                <option value="certum">Certum</option>
                <option value="sectigo">Sectigo</option>
                <option value="digicert">DigiCert</option>
                <option value="globalsign">GlobalSign</option>
                <option value="sheca">SHECA</option>
              </select>
            </div>
            <button type="submit">批量验证</button>
          </form>
          <div id="verify-result" class="result" style="display: none"></div>
        </div>

        <!-- 链接查询 -->
        <div id="link-tab" class="tab-content" style="display: none">
          <form onsubmit="queryLink(); return false;">
            <div class="form-group">
              <label for="link-url">链接地址</label>
              <input type="text" id="link-url" placeholder="请输入链接地址" />
            </div>
            <button type="submit">查询链接</button>
          </form>
          <div id="link-result" class="result" style="display: none"></div>
        </div>

        <!-- DNS查询 -->
        <div id="dns-tab" class="tab-content" style="display: none">
          <form onsubmit="queryDNS(); return false;">
            <div class="form-group">
              <label for="dns-domain">域名</label>
              <input type="text" id="dns-domain" placeholder="请输入域名" />
            </div>
            <div class="form-group">
              <label for="dns-type">记录类型</label>
              <select id="dns-type">
                <option value="A">A</option>
                <option value="AAAA">AAAA</option>
                <option value="CNAME">CNAME</option>
                <option value="MX">MX</option>
                <option value="TXT">TXT</option>
                <option value="NS">NS</option>
                <option value="CAA">CAA</option>
              </select>
            </div>
            <button type="submit">查询</button>
          </form>
          <div id="dns-result" class="result" style="display: none"></div>
        </div>

        <!-- WHOIS查询 -->
        <div id="whois-tab" class="tab-content" style="display: none">
          <form onsubmit="queryWhois(); return false;">
            <div class="form-group">
              <label for="whois-domain">域名</label>
              <input type="text" id="whois-domain" placeholder="请输入域名" />
            </div>
            <button type="submit">查询</button>
          </form>
          <div id="whois-result" class="result" style="display: none"></div>
        </div>
      </div>
    </div>

    <script>
      const API_BASE = "/api";
      let regions = [];
      let currentRegion = "";

      // HTML转义函数
      function escapeHtml(text) {
        const div = document.createElement("div");
        div.textContent = text;
        return div.innerHTML;
      }

      // 加载区域信息
      async function loadRegions() {
        try {
          const response = await fetch(`${API_BASE}/regions`, {
            cache: 'no-store'  // 禁止缓存，确保获取最新数据
          });
          const data = await response.json();

          if (data.code === 1) {
            regions = data.data.regions;
            currentRegion = data.data.currentRegion;

            const select = document.getElementById("region-select");
            select.innerHTML = "";

            regions.forEach((region) => {
              const option = document.createElement("option");
              option.value = region.id;
              option.textContent = region.name;
              if (region.id === currentRegion) {
                option.selected = true;
              }
              select.appendChild(option);
            });
          }
        } catch (error) {
          console.error("Failed to load regions:", error);
        }
      }

      // 切换区域
      function switchRegion(regionId) {
        const region = regions.find((r) => r.id === regionId);
        if (region && region.url) {
          // 保留当前URL参数
          const params = new URLSearchParams(window.location.search);
          const newUrl = region.url + window.location.pathname;

          if (params.toString()) {
            window.location.href = newUrl + "?" + params.toString();
          } else {
            window.location.href = newUrl;
          }
        }
      }

      function showTab(tabName) {
        // 隐藏所有标签页
        document.querySelectorAll(".tab-content").forEach((tab) => {
          tab.style.display = "none";
        });

        // 移除所有active类
        document.querySelectorAll(".tab").forEach((tab) => {
          tab.classList.remove("active");
        });

        // 显示选中的标签页
        document.getElementById(tabName + "-tab").style.display = "block";

        // 添加active类到对应的标签按钮
        const tabButtons = document.querySelectorAll(".tab");
        const tabNames = ["verify", "dns", "whois", "link"];
        const tabIndex = tabNames.indexOf(tabName);
        if (tabIndex !== -1 && tabButtons[tabIndex]) {
          tabButtons[tabIndex].classList.add("active");
        }
      }

      function updateURLParams(params) {
        const url = new URL(window.location);

        // 清除现有的相关参数
        url.searchParams.delete("domain");
        url.searchParams.delete("url");
        url.searchParams.delete("brand");
        url.searchParams.delete("type");
        url.searchParams.delete("tab");
        url.searchParams.delete("domains");

        // 添加新参数
        Object.keys(params).forEach((key) => {
          if (params[key]) {
            url.searchParams.set(key, params[key]);
          }
        });

        // 更新浏览器URL（不刷新页面）
        window.history.replaceState({}, "", url);
      }

      async function queryDNS() {
        const domainInput = document.getElementById("dns-domain");
        const domain = domainInput.value;
        const type = document.getElementById("dns-type").value;

        if (!domain) {
          alert("请输入域名");
          return;
        }

        // 先写入用户输入，稍后用服务端清洗后的域名覆盖
        updateURLParams({ domain: domain, type: type, tab: "dns" });

        const resultDiv = document.getElementById("dns-result");
        resultDiv.innerHTML = '<div class="loading"></div> 查询中...';
        resultDiv.style.display = "block";

        try {
          const response = await fetch(`${API_BASE}/dns/query`, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            cache: 'no-store',  // 禁止缓存，确保DNS查询结果为最新
            body: JSON.stringify({ domain, type }),
          });

          const data = await response.json();

          if (data.code === 1) {
            // 使用后端清洗后的域名回填输入框与URL
            const cleaned =
              (data.data && (data.data.display_domain || data.data.domain)) ||
              domain;
            if (cleaned) {
              try {
                domainInput.value = cleaned;
              } catch (e) {}
              updateURLParams({ domain: cleaned, type: type, tab: "dns" });
            }
            let html = `<h3>查询结果</h3>`;
            const dispDomain =
              (data.data && (data.data.display_domain || data.data.domain)) ||
              "";
            html += `<p><strong>域名:</strong> ${escapeHtml(dispDomain)}</p>`;

            // 显示使用的 DNS 服务器
            if (data.data && data.data.dns_servers && Array.isArray(data.data.dns_servers)) {
              const servers = data.data.dns_servers.map(s => s.replace(':53', '')).join(', ');
              html += `<p><strong>DNS 服务器:</strong> ${servers}</p>`;
            }

            if (
              String(type).toUpperCase() === "ALL" &&
              data.data &&
              data.data.result
            ) {
              const res = data.data.result;
              const sections = [
                { key: "a", title: "A" },
                { key: "aaaa", title: "AAAA" },
                { key: "cname", title: "CNAME" },
                { key: "mx", title: "MX" },
                { key: "txt", title: "TXT" },
                { key: "ns", title: "NS" },
                { key: "caa", title: "CAA" },
              ];
              sections.forEach((sec) => {
                const list = res[sec.key];
                html += `<h4>${sec.title}</h4>`;
                if (Array.isArray(list) && list.length) {
                  html += "<pre>" + JSON.stringify(list, null, 2) + "</pre>";
                } else {
                  html += "<p>无</p>";
                }
              });
              resultDiv.innerHTML = html;
            } else {
              html += `<p><strong>类型:</strong> ${data.data.type}</p>`;
              if (data.data.records && data.data.records.length > 0) {
                html += "<h4>记录:</h4>";
                html +=
                  "<pre>" +
                  JSON.stringify(data.data.records, null, 2) +
                  "</pre>";
              } else {
                html += "<p>未找到记录</p>";
              }
              resultDiv.innerHTML = html;
            }
          } else {
            resultDiv.innerHTML = `<p style="color: red;">错误: ${data.msg}</p>`;
          }
        } catch (error) {
          resultDiv.innerHTML = `<p style="color: red;">请求失败: ${error.message}</p>`;
        }
      }

      // 单域验证已移除；请使用 verifyDomains（批量）
      // 新增：批量验证域名（每行一个）
      async function verifyDomains() {
        const textarea = document.getElementById("verify-domains");
        const brand = document.getElementById("verify-brand").value;
        const raw = textarea && textarea.value ? textarea.value : "";
        const lines = raw
          .split(/\r?\n/)
          .map((s) => s.trim())
          .filter(Boolean);
        if (lines.length === 0) {
          alert("请输入至少一个域名");
          return;
        }

        // URL 预写参数：单域名写 domain，多域名不写 domain（避免与 domains 冲突）
        if (lines.length === 1) {
          updateURLParams({ domain: lines[0], brand: brand, tab: "verify" });
        } else {
          updateURLParams({ brand: brand, tab: "verify" });
        }

        const resultDiv = document.getElementById("verify-result");
        resultDiv.innerHTML = '<div class="loading"></div> 验证中...';
        resultDiv.style.display = "block";

        try {
          const url = `${API_BASE}/domain/issue-verify`;
          const payload = { brand, domains: lines.join(",") };
          const resp = await fetch(url, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(payload),
            cache: 'no-store',  // 禁止缓存，确保验证结果为最新
          });
          const data = await resp.json();

          if (data.code === 1) {
            let html = "";
            let displayList = [];
            const allValid = data.data.all_valid;

            // 添加总体状态提示
            if (allValid) {
              html += `<div style="background: #d4edda; color: #155724; padding: 12px; border-radius: 6px; margin-bottom: 15px;">`;
              html += `<strong>✅ 所有域名验证通过！</strong>`;
              html += `</div>`;
            }

            html += `<h3>批量验证结果（品牌：${brand}）</h3>`;
            const results = data.data.results || [];

            // 如果全部通过，简单显示域名列表
            if (allValid && results.length > 0) {
              html += `<div style="border: 1px solid #28a745; padding: 15px; border-radius: 6px; background: #f8f9fa;">`;
              html += `<p><strong>验证通过的域名（${results.length}个）：</strong></p>`;
              html += '<ul style="margin: 10px 0; padding-left: 20px;">';
              results.forEach((item) => {
                const dispDomain = item.display_domain || item.domain || "";
                html += `<li>${escapeHtml(dispDomain)}</li>`;
              });
              html += "</ul>";
              html += "</div>";
            } else {
              // 有失败的，显示详细信息
              results.forEach((item) => {
                html += renderVerifyItem(item);
              });
            }

            displayList = results
              .map((it) => (it && (it.display_domain || it.domain)) || "")
              .filter(Boolean);
            resultDiv.innerHTML = html;
            // 成功后：URL 仅记录前10个，输入框回填全部清洗后的显示域名
            if (displayList.length) {
              if (displayList.length === 1) {
                updateURLParams({
                  domain: displayList[0],
                  brand: brand,
                  tab: "verify",
                });
              } else {
                const enc = displayList
                  .slice(0, 10)
                  .map((d) => encodeURIComponent(d))
                  .join(",");
                updateURLParams({ brand: brand, tab: "verify", domains: enc });
              }
              try {
                const textarea = document.getElementById("verify-domains");
                if (textarea) textarea.value = displayList.join("\n");
              } catch (e) {}
            }
          } else {
            // 失败：后端 errors 里包含每个域名的详细结果
            let html = `<p style=\"color: red;\">错误: ${
              data.msg || "验证失败"
            }</p>`;
            const errs = Array.isArray(data.errors) ? data.errors : [];
            if (errs.length) {
              html += "<h4>详细结果</h4>";
              errs.forEach((item) => {
                html += renderVerifyItem(item);
              });
            }
            resultDiv.innerHTML = html;
          }
        } catch (e) {
          resultDiv.innerHTML = `<p style=\"color: red;\">请求失败: ${e.message}</p>`;
        }
      }

      function renderVerifyItem(item) {
        let html = `<div style=\"border:1px solid #ddd; padding:12px; margin:10px 0; border-radius:6px;\">`;
        const dispDomain = item.display_domain || item.domain || "";
        html += `<p><strong>域名:</strong> ${escapeHtml(dispDomain)}</p>`;
        html += `<p><strong>验证状态:</strong> ${
          item.valid ? "✅ 通过" : "❌ 失败"
        }</p>`;
        if (item.brand) html += `<p><strong>品牌:</strong> ${item.brand}</p>`;
        if (item.message)
          html += `<p><strong>说明:</strong> ${item.message}</p>`;
        const chain = item.cname_chain_display || item.cname_chain;
        if (Array.isArray(chain) && chain.length > 1) {
          html += `<p><strong>CNAME链:</strong> ${chain
            .map(escapeHtml)
            .join(" → ")}</p>`;
        }
        if (Array.isArray(item.caa_records) && item.caa_records.length) {
          html += "<p><strong>CAA记录:</strong></p>";
          html +=
            "<pre>" + JSON.stringify(item.caa_records, null, 2) + "</pre>";
        }
        if (Array.isArray(item.errors) && item.errors.length) {
          html += "<p><strong>错误:</strong></p>";
          html += "<pre>" + JSON.stringify(item.errors, null, 2) + "</pre>";
        }
        if (
          Array.isArray(item.ns_missing_roots) &&
          item.ns_missing_roots.length
        ) {
          html += "<p><strong>缺少NS的根域名:</strong></p>";
          html += item.ns_missing_roots
            .map(escapeHtml)
            .map((x) => `<p>${x}</p>`)
            .join("");
        }
        html += "</div>";
        return html;
      }

      // 全局格式化日期时间函数
      function formatDateTime(dateStr) {
        if (!dateStr || dateStr === "未知") return dateStr;
        try {
          const date = new Date(dateStr);
          if (isNaN(date.getTime())) {
            return dateStr;
          }

          // 检查是否只有日期（时间为 00:00:00）
          if (
            date.getHours() === 0 &&
            date.getMinutes() === 0 &&
            date.getSeconds() === 0
          ) {
            return date.toLocaleDateString("zh-CN");
          }

          // 完整的日期时间
          return date
            .toLocaleString("zh-CN", {
              year: "numeric",
              month: "2-digit",
              day: "2-digit",
              hour: "2-digit",
              minute: "2-digit",
              second: "2-digit",
              hour12: false,
            })
            .replace(/\//g, "-");
        } catch (e) {
          return dateStr;
        }
      }

      async function queryWhois() {
        const whoisInput = document.getElementById("whois-domain");
        const domain = whoisInput.value;

        if (!domain) {
          alert("请输入域名");
          return;
        }

        // 先写入用户输入，稍后用服务端清洗后的域名覆盖
        updateURLParams({ domain: domain, tab: "whois" });

        const resultDiv = document.getElementById("whois-result");
        resultDiv.innerHTML = '<div class="loading"></div> 查询中...';
        resultDiv.style.display = "block";

        try {
          const response = await fetch(`${API_BASE}/whois/query`, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            cache: 'no-store',  // 禁止缓存，确保WHOIS查询结果为最新
            body: JSON.stringify({ domain }),
          });

          const data = await response.json();

          if (data.code === 1) {
            const d = data.data || {};
            // 使用后端清洗后的域名回填输入框与URL
            const cleaned = d.display_domain || d.domain || domain;
            if (cleaned) {
              try {
                whoisInput.value = cleaned;
              } catch (e) {}
              updateURLParams({ domain: cleaned, tab: "whois" });
            }
            let html = `<h3>WHOIS查询结果</h3>`;
            const disp = d.display_domain || d.domain || "";
            html += `<p><strong>域名:</strong> ${escapeHtml(disp)}</p>`;
            html += `<p><strong>注册商:</strong> ${d.registrar || ""}</p>`;

            if (d.created_date && d.created_date !== "未知") {
              html += `<p><strong>注册时间:</strong> ${formatDateTime(
                d.created_date
              )}</p>`;
            }
            if (d.updated_date && d.updated_date !== "未知") {
              html += `<p><strong>更新时间:</strong> ${formatDateTime(
                d.updated_date
              )}</p>`;
            }
            if (d.expiry_date && d.expiry_date !== "未知") {
              html += `<p><strong>到期时间:</strong> ${formatDateTime(
                d.expiry_date
              )}</p>`;
            }
            if (d.status || d.status_info) {
              html += "<p><strong>域名状态:</strong></p>";

              // 如果有详细状态信息，显示简化的中英文
              if (d.status_info && Array.isArray(d.status_info)) {
                html +=
                  '<div style="margin-left: 16px; font-size: 14px; line-height: 1.6;">';
                d.status_info.forEach((info) => {
                  const statusColor =
                    info.code === "ok"
                      ? "green"
                      : info.type === "client"
                      ? "#ff6b00"
                      : info.type === "server"
                      ? "#d32f2f"
                      : "#666";
                  html += `<div style="margin: 2px 0; color: ${statusColor};">`;
                  html += `${escapeHtml(info.name_cn)} (${escapeHtml(
                    info.name
                  )})`;
                  html += "</div>";
                });
                html += "</div>";
              } else if (d.status) {
                // 降级显示：仅显示状态码
                const statuses = Array.isArray(d.status)
                  ? d.status
                  : String(d.status)
                      .split(/[,;]+/)
                      .map((s) => s.trim())
                      .filter(Boolean);
                if (statuses.length) {
                  html +=
                    '<div style="margin-left: 16px; font-size: 14px; line-height: 1.6;">';
                  statuses.forEach((s) => {
                    html += `<div style="margin: 2px 0;">• ${escapeHtml(
                      s
                    )}</div>`;
                  });
                  html += "</div>";
                }
              }
            }
            if (Array.isArray(d.name_servers) && d.name_servers.length > 0) {
              html += "<h4>名称服务器:</h4>";
              d.name_servers.forEach((ns) => {
                html += `<div style="font-size: 14px; line-height: 1.6;">${ns}</div>`;
              });
            }
            if (d.dnssec) {
              const v = String(d.dnssec).toLowerCase();
              let label = v;
              if (v === "unsigned") label = "未签名 (unsigned)";
              else if (v === "signeddelegation" || v === "signed")
                label = "已签名 (signed)";
              html += `<p><strong>DNSSEC:</strong> ${escapeHtml(label)}</p>`;
            }
            if (d.raw && d.raw !== "未知") {
              html += "<h4>原始WHOIS数据:</h4>";
              html += `<pre style="background: #f5f5f5; padding: 10px; border-radius: 4px; font-size: 12px; max-height: 300px; overflow-y: auto;">${escapeHtml(
                d.raw
              )}</pre>`;
            }
            resultDiv.innerHTML = html;
          } else {
            resultDiv.innerHTML = `<p style="color: red;">错误: ${data.msg}</p>`;
          }
        } catch (error) {
          resultDiv.innerHTML = `<p style="color: red;">请求失败: ${error.message}</p>`;
        }
      }

      async function queryLink() {
        const url = document.getElementById("link-url").value;

        if (!url) {
          alert("请输入链接地址");
          return;
        }

        // 更新URL参数
        updateURLParams({ url: url, tab: "link" });

        const resultDiv = document.getElementById("link-result");
        resultDiv.innerHTML = '<div class="loading"></div> 查询中...';
        resultDiv.style.display = "block";

        try {
          const response = await fetch(`${API_BASE}/link/query`, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            cache: 'no-store',  // 禁止缓存，确保链接检查结果为最新
            body: JSON.stringify({ url }),
          });

          const data = await response.json();

          if (data.code === 1) {
            let html = `<h3>链接查询结果</h3>`;
            html += `<p><strong>查询链接:</strong> ${escapeHtml(url)}</p>`;

            // 判断返回的数据结构类型
            // 如果data.data有http或https字段，说明是多协议查询结果（ProtocolVerificationResult）
            // 如果data.data直接有url、success等字段，说明是单协议查询结果（LinkVerificationResult）
            const isMultiProtocol = data.data && (data.data.http || data.data.https);
            
            if (isMultiProtocol) {
              // 多协议查询结果
              const protocols = ["http", "https"];
              protocols.forEach((protocol) => {
                const result = data.data[protocol];
                if (result) {
                  html += renderLinkResult(result, protocol);
                }
              });
            } else {
              // 单协议查询结果
              const result = data.data;
              if (result) {
                // 从URL中提取协议
                const urlLower = url.toLowerCase().trim();
                let protocol = "unknown";
                if (urlLower.startsWith('https://')) {
                  protocol = 'https';
                } else if (urlLower.startsWith('http://')) {
                  protocol = 'http';
                }
                html += renderLinkResult(result, protocol);
              }
            }

            resultDiv.innerHTML = html;
          } else {
            resultDiv.innerHTML = `<p style="color: red;">错误: ${data.msg}</p>`;
          }
        } catch (error) {
          resultDiv.innerHTML = `<p style="color: red;">请求失败: ${error.message}</p>`;
        }
      }

      // 渲染单个链接查询结果
      function renderLinkResult(result, protocol) {
        let html = "";
        html += `<div style="border: 1px solid #ddd; margin: 15px 0; padding: 15px; border-radius: 6px; background: ${
          protocol === "https" ? "#f0f8ff" : "#f8f8f8"
        };">`;
        html += `<h4 style="color: ${
          protocol === "https" ? "#1976D2" : "#666"
        }; margin-bottom: 10px;">${protocol.toUpperCase()}</h4>`;

        html += `<p><strong>URL:</strong> ${escapeHtml(result.url)}</p>`;

        if (result.success) {
          html += `<p><strong>状态:</strong> <span style="color: green;">✅ 可访问 (${result.status_code})</span></p>`;
          if (result.response_time) {
            html += `<p><strong>响应时间:</strong> ${Math.round(
              result.response_time / 1000000
            )}ms</p>`;
          }
          if (result.final_url && result.final_url !== result.url) {
            html += `<p><strong>最终URL:</strong> ${escapeHtml(
              result.final_url
            )}</p>`;
          }
          if (result.redirect_count > 0) {
            html += `<p><strong>重定向次数:</strong> ${result.redirect_count}</p>`;
          }
          if (result.content_type) {
            html += `<p><strong>内容类型:</strong> ${escapeHtml(
              result.content_type
            )}</p>`;
          }
          if (result.content_length > 0) {
            html += `<p><strong>内容大小:</strong> ${result.content_length} bytes</p>`;
          }

          if (result.content) {
            html += '<h5 style="margin-top: 10px;">内容预览:</h5>';
            const contentPreview = result.content.substring(0, 1000);
            html += `<pre style="background: white; padding: 10px; border: 1px solid #ddd; border-radius: 4px; max-height: 300px; overflow-y: auto; font-size: 12px; white-space: pre-wrap; word-wrap: break-word;">${escapeHtml(
              contentPreview
            )}</pre>`;
            if (result.content.length > 1000) {
              html += `<p style="color: #666; font-size: 12px;">（内容已截断，显示前1000字符）</p>`;
            }
          }
        } else {
          html += `<p><strong>状态:</strong> <span style="color: red;">❌ 无法访问</span></p>`;
          if (result.error) {
            html += `<p><strong>错误:</strong> ${escapeHtml(result.error)}</p>`;
          }
        }

        html += "</div>";
        return html;
      }

      // 域名输入框同步功能
      function syncDomains() {
        const verifyDomainsTextarea = document.getElementById("verify-domains");
        const dnsDomainInput = document.getElementById("dns-domain");
        const whoisDomainInput = document.getElementById("whois-domain");

        // 多行域名 -> 单行域名（提取第一个，自动去除空格）
        verifyDomainsTextarea.addEventListener("input", function() {
          const lines = this.value.split(/\r?\n/).map(s => s.trim()).filter(Boolean);
          const firstDomain = lines.length > 0 ? lines[0] : "";
          if (dnsDomainInput) dnsDomainInput.value = firstDomain;
          if (whoisDomainInput) whoisDomainInput.value = firstDomain;
        });

        // DNS域名 -> 多行域名第一行（自动去除空格）
        dnsDomainInput.addEventListener("input", function() {
          const trimmedValue = this.value.trim();
          this.value = trimmedValue;
          
          if (verifyDomainsTextarea) {
            const lines = verifyDomainsTextarea.value.split(/\r?\n/).map(s => s.trim()).filter(Boolean);
            if (lines.length === 0) {
              verifyDomainsTextarea.value = trimmedValue;
            } else {
              lines[0] = trimmedValue;
              verifyDomainsTextarea.value = lines.join("\n");
            }
          }
          if (whoisDomainInput && whoisDomainInput.value !== trimmedValue) {
            whoisDomainInput.value = trimmedValue;
          }
        });

        // WHOIS域名 -> 多行域名第一行（自动去除空格）
        whoisDomainInput.addEventListener("input", function() {
          const trimmedValue = this.value.trim();
          this.value = trimmedValue;
          
          if (verifyDomainsTextarea) {
            const lines = verifyDomainsTextarea.value.split(/\r?\n/).map(s => s.trim()).filter(Boolean);
            if (lines.length === 0) {
              verifyDomainsTextarea.value = trimmedValue;
            } else {
              lines[0] = trimmedValue;
              verifyDomainsTextarea.value = lines.join("\n");
            }
          }
          if (dnsDomainInput && dnsDomainInput.value !== trimmedValue) {
            dnsDomainInput.value = trimmedValue;
          }
        });
      }

      // 处理URL参数
      window.onload = function () {
        // 加载区域信息
        loadRegions();
        
        // 初始化域名同步功能
        syncDomains();

        const urlParams = new URLSearchParams(window.location.search);

        // 获取URL参数
        const domain = urlParams.get("domain");
        const domainsParam = urlParams.get("domains");
        const url = urlParams.get("url");
        const brand = urlParams.get("brand");
        const tab = urlParams.get("tab");
        const type = urlParams.get("type");

        // 设置品牌选项
        if (brand) {
          const brandSelects = document.querySelectorAll(
            'select[id$="-brand"]'
          );
          brandSelects.forEach((select) => {
            if (select.querySelector(`option[value="${brand}"]`)) {
              select.value = brand;
            }
          });
        }

        // 根据参数切换到对应标签并填充数据
        if (tab) {
          showTab(tab);
        }

        if (domain || domainsParam) {
          // 域名验证
          const verifyDomainsInput = document.getElementById("verify-domains");
          if (verifyDomainsInput) {
            if (domainsParam) {
              // 逐项解码，再转为多行展示
              verifyDomainsInput.value = domainsParam
                .split(",")
                .map((x) => decodeURIComponent(x))
                .join("\n");
            } else if (domain) {
              verifyDomainsInput.value = domain;
            }
            if (tab === "verify" || (!tab && !url)) {
              showTab("verify");
              if (brand) verifyDomains();
            }
          }

          // DNS查询
          const dnsDomainInput = document.getElementById("dns-domain");
          if (dnsDomainInput) {
            dnsDomainInput.value = domain;
            if (tab === "dns") {
              showTab("dns");
              if (type) {
                document.getElementById("dns-type").value = type;
              }
              queryDNS();
            }
          }

          // WHOIS查询
          const whoisDomainInput = document.getElementById("whois-domain");
          if (whoisDomainInput) {
            whoisDomainInput.value = domain;
            if (tab === "whois") {
              showTab("whois");
              queryWhois();
            }
          }
        }

        if (url) {
          // 链接查询
          const linkUrlInput = document.getElementById("link-url");
          if (linkUrlInput) {
            linkUrlInput.value = url;
            if (tab === "link" || !domain) {
              showTab("link");
              queryLink();
            }
          }
        }
      };
    </script>
  </body>
</html>
